//
//  WMEUserViewController.m
//  everyDay_duiTang
//
//  Created by 恩叔 on 16/1/23.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import "WMEUserViewController.h"
#import "WMEUserModel.h"

#import "WMEFirstPageInformationVC.h"
#import <AFNetworking.h>
#import "WMEUserBack.h"
#import "WMEAlbumViewController.h"
#import "WMEClubListViewController.h"
#import "WMEClubInformationModel.h"
#import "WMEImageViewController.h"
#import "WMEUserCollectionReusableView.h"
#import "WMEUserCollectionViewCell.h"
#import <MJRefresh.h>
#pragma mark - 用户界面
@interface WMEUserViewController ()<pushActionDelegate, pushClubActionDelegate ,pushImgViewDelegate,UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
//@property (nonatomic, retain)NSMutableArray *dataArr;
//@property (nonatomic, retain)NSMutableArray *nameArr;
//@property (nonatomic, retain)NSMutableDictionary *keyDic;
//@property (nonatomic, retain)NSMutableDictionary *dayDic;
//@property (nonatomic, retain)NSMutableArray *dayArr;
@property (nonatomic, retain) NSMutableArray *dayArr; /**< 保存的日期数组 */
@property (nonatomic, retain) NSMutableDictionary *photoDic; /**< 所有的照片数据字典 */
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)NSNumber *next_start;
@property (nonatomic, retain)NSNumber *total;
@property (nonatomic, copy)NSString *urlStr;
@property (nonatomic, retain)UIButton *barButton;
@end

@implementation WMEUserViewController

- (void)dealloc
{
    [_dayArr release];
    [_photoDic release];
    [_collectionView release];
    [_next_start release];
    [_total release];
    [_urlStr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(liftAction)];
//    self.barButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    _barButton.frame = CGRectMake(20, 10, 30, 20);
//    [_barButton setTitle:@"返回" forState:UIControlStateNormal];
//    [_barButton addTarget:self action:@selector(liftAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.navigationController.navigationBar addSubview:_barButton];

    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"用户首页";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createView];
    [self data];
//    if (_next_start.integerValue < _total.integerValue) {
//        [self loadingFunction];
//    }
    [self loadingFunction];
}
- (void)createView
{
//    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
//    _tableView.delegate = self;
//    _tableView.dataSource = self;
//    WMEUserBack *beijing = [[WMEUserBack alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width)];
//    beijing.dic = _userDic;
//    beijing.delegate = self;
//    beijing.clubDelegate = self;
//    beijing.imgDelegate = self;
//    _tableView.tableHeaderView = beijing;
//    [self.view addSubview:_tableView];
//    [beijing release];
//    [_tableView release];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((WIDTH - 40 *  WIDTH / 414)/ 3, (WIDTH - 40 * WIDTH / 414) / 3);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.headerReferenceSize = CGSizeMake(100, 30);

    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.contentInset = UIEdgeInsetsMake(WIDTH, 0, 0, 0);
    WMEUserBack *beijing = [[WMEUserBack alloc] initWithFrame:CGRectMake(0, -WIDTH, WIDTH, WIDTH)];
    beijing.dic = _userDic;
    beijing.delegate = self;
    beijing.clubDelegate = self;
    beijing.imgDelegate = self;
    [self.collectionView addSubview:beijing];
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[WMEUserCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collctionHead"];
    [beijing release];
    [layout release];
    [_collectionView release];
}
- (void)data
{
//    self.nameArr = [NSMutableArray array];
//    self.dayDic = [NSMutableDictionary dictionary];
//    self.dayArr = [NSMutableArray array];
//    self.keyDic = [NSMutableDictionary dictionary];
    
    NSString *temp = @"http://www.duitang.com/napi/blog/list/by_user/?__dtac=%257B%2522_r%2522%253A%2520%2522970614%2522%257D&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&include_fields=album%2Csender%2Cicon_url&limit=40&locale=zh_CN&only_root=0&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320&start=0&user_id=9358252";
    self.urlStr = [temp stringByReplacingOccurrencesOfString:@"id=9358252" withString:[NSString stringWithFormat:@"id=%@", _userId]];
    //AFN网络请求
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
//    __weak WMEUserViewController *vc = self;
    
    [data GET:_urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"responseObject:%@", responseObject);
        NSArray *tempArr = responseObject[@"data"][@"object_list"];
        self.next_start = responseObject[@"data"][@"next_start"];
        self.total = responseObject[@"data"][@"total"];
//        NSLog(@"tempArr:%@", tempArr);
        
//        self.dataArr = [WMEUserModel modelHandlerWithArray:tempArr];
//        
//        for (WMEUserModel *tempModel in _dataArr) {
//            NSString *string = [self jisuanTime:tempModel.add_datetime_ts];
//            NSMutableArray *mArr1 = _keyDic[string];
//            if (mArr1) {
//                [mArr1 addObject:tempModel];
//            }else{
//                NSMutableArray *newmArr = [NSMutableArray array];
//                [newmArr addObject:tempModel];
//                [_keyDic setObject:newmArr forKey:string];
//            }
//            NSString *dayStr = [self jisuanTIME:tempModel.add_datetime_ts];
//            NSMutableArray *dArr = _dayDic[dayStr];
//            if (dArr) {
//                [dArr addObject:tempModel];
//            }else{
//                NSMutableArray *newDArr = [NSMutableArray array];
//                [newDArr addObject:tempModel];
//                [_dayDic setObject:newDArr forKey:dayStr];
//            }
//        }
//        _nameArr = [[[[_keyDic.allKeys  sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects] mutableCopy];
//        
//        _dayArr = [[[[_dayDic.allKeys sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects]mutableCopy];
//        
//        NSLog(@"%@~~~%@", _keyDic.allKeys, _keyDic.allValues);
//        NSLog(@"#%@",_nameArr);
//        NSLog(@"%@---%@", _dayDic.allKeys, _dayDic.allValues);
//        NSLog(@"!%@", _dayArr);
//        
//        [_tableView reloadData];
        // 初始化
        self.photoDic = [NSMutableDictionary dictionary];
        self.dayArr = [NSMutableArray array];
        // 数据解析
        for (NSDictionary *dic in tempArr) {
            // 创建model
            WMEUserModel *m = [[WMEUserModel alloc] init];
            // 将遍历到的字典转换成model类保存
            [m setValuesForKeysWithDictionary:dic];
            // 获取当前model中需要当key值的数据
            NSString *days = [m.add_datetime substringToIndex:5];
            // 创建days(key值)对应的数组
            NSMutableArray *photo = _photoDic[days];
            // 判断数组是否存在
            if(photo){
                // 存在将model类添加
                [photo addObject:m];
            }else{
                // 不存在创建新的数组
                NSMutableArray *newPhoto = [NSMutableArray array];
                // 添加model类
                [newPhoto addObject:m];
                // 把数据保存到字典中
                [_photoDic setObject:newPhoto forKey:days];
            }
            // 将所有的key值保存
            if (![_dayArr containsObject:days]) {
                [_dayArr addObject:days];
            }
            
            
        }
        NSLog(@"%@", _photoDic);
        [_collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}
//#pragma mark -tableView协议方法
////分区数
//#pragma mark -分区数
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    if (_nameArr.count) {
//        return _nameArr.count;
//    }
//    return 0;
//}
////每个分区cell的个数
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
////    if (_keyDic.count) {
////        NSLog(@"dayArr:%ld", _keyDic.count);
////        return _keyDic.count ;
////    }
////    if (_nameArr.count) {
////        NSString *str =_nameArr[section];
////        NSArray *arr = _keyDic[str];
////        return arr.count;
////    }
//    int i = 0;
//    if (_dayArr.count) {
//        NSString *name = _nameArr[section];
//        for (NSString *temp in _dayArr) {
//            if ([temp containsString:name]) {
//                i ++;
//            }
//        }
//        return i;
//    }
//    return 0;
//}
////设置cell
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    [tableView registerClass:[WMEUserTableViewCell class] forCellReuseIdentifier:@"userCell"];
//    WMEUserTableViewCell *userCell = [tableView dequeueReusableCellWithIdentifier:@"userCell" forIndexPath:indexPath];
////    if (_dayArr.count){
////        NSString *strTemp = _dayArr[indexPath.item];
////        NSArray *arrr = _dayDic[strTemp];
////        userCell.array = arrr;
////        return userCell;
////    }
//    if (_nameArr.count) {
//        NSString *yue = _nameArr[indexPath.section];
//        NSLog(@"%@",yue);
//        if ([_dayArr[indexPath.row] containsString:yue]) {
//            NSString *cellStr = _dayArr[indexPath.row];
//            NSArray *cellArr = _dayDic[cellStr];
//            userCell.array = cellArr;
//            userCell.dayStr = [cellStr substringFromIndex:8];
//            userCell.delegate = self;
//            NSLog(@"%@", cellStr);
//            return userCell;
//        }
//    }
//    return userCell;
//}
- (void)liftAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
////cell的高度
//#pragma mark -cell的高度 正确
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (_nameArr.count) {
//        NSString *key = _dayArr[indexPath.row];
//        NSArray *arrrr = _dayDic[key];
////            NSLog(@"cell gao:%ld",arrrr.count);
//        CGFloat h = 0;
////        CGFloat h = 107 * arrrr.count/3 + 20 + 107;
//        if (arrrr.count % 3 == 0) {
//            h = 107 * (int)(arrrr.count / 3) + 40;
//        }else{
//            h = 107 * (int)((arrrr.count) / 3 + 1) + 40;
//        }
////        NSLog(@"height:%lf",h);
//        return h ;
//    }
//    return 0;
//    
//}
////分区名
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    if (_nameArr.count) {
//        return _nameArr[section];
//    }
//    return @"";
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 50;
//}
// 分区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _dayArr.count;
}
// collection头高属性
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    WMEUserCollectionReusableView *header = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"collctionHead" forIndexPath:indexPath];
    header.name.text = _dayArr[indexPath.section];
    return header;
}

// 个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_photoDic[_dayArr[section]] count];
}
// 对cell赋值
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [_collectionView registerClass:[WMEUserCollectionViewCell class] forCellWithReuseIdentifier:@"userCell"];
    WMEUserCollectionViewCell *userCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"userCell" forIndexPath:indexPath];
    WMEUserModel *model = _photoDic[_dayArr[indexPath.section]][indexPath.item];
    if (_photoDic != nil) {
        userCell.model = model;
    }
    return userCell;
}
// 点击跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    WMEFirstPageInformationVC *informationVC = [[WMEFirstPageInformationVC alloc] init];
    informationVC.hidesBottomBarWhenPushed = YES;
    WMEUserModel *m = _photoDic[_dayArr[indexPath.section]][indexPath.item];
    informationVC.jiekou = m.Id.stringValue;
    [self.navigationController pushViewController:informationVC animated:YES];
}
#pragma mark -刷新
- (void)refreshFunction
{
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.dayArr removeAllObjects];
        [self.photoDic removeAllObjects];
        [self data];
        [self.collectionView.mj_header endRefreshing];
    }];
}

- (void)loadingFunction
{
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *url = [_urlStr stringByReplacingOccurrencesOfString:@"start=0" withString:[NSString stringWithFormat:@"start=%@", _next_start]];
        AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
        //    __weak WMEUserViewController *vc = self;
        
        [data GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //        NSLog(@"responseObject:%@", responseObject);
            NSArray *tempArr = responseObject[@"data"][@"object_list"];
            self.next_start = responseObject[@"data"][@"next_start"];
            self.total = responseObject[@"data"][@"total"];
            // 数据解析
            for (NSDictionary *dic in tempArr) {
                // 创建model
                WMEUserModel *m = [[WMEUserModel alloc] init];
                // 将遍历到的字典转换成model类保存
                [m setValuesForKeysWithDictionary:dic];
                // 获取当前model中需要当key值的数据
                NSString *days = [m.add_datetime substringToIndex:5];
                // 创建days(key值)对应的数组
                NSMutableArray *photo = _photoDic[days];
                // 判断数组是否存在
                if(photo){
                    // 存在将model类添加
                    [photo addObject:m];
                }else{
                    // 不存在创建新的数组
                    NSMutableArray *newPhoto = [NSMutableArray array];
                    // 添加model类
                    [newPhoto addObject:m];
                    // 把数据保存到字典中
                    [_photoDic setObject:newPhoto forKey:days];
                }
                // 将所有的key值保存
                if (![_dayArr containsObject:days]) {
                    [_dayArr addObject:days];
                }
            }
            NSLog(@"%@", _photoDic);
            [_collectionView reloadData];
            if (_next_start.integerValue >_total.integerValue) {
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [_collectionView.mj_footer endRefreshing];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            nil;
        }];
    }];
}

//#pragma mark - 自定义协议的方法
//- (void)pushInformation:(NSString *)str
//{
//    WMEFirstPageInformationVC *informationVC = [[WMEFirstPageInformationVC alloc] init];
//    informationVC.jiekou = str;
//    [self.navigationController pushViewController:informationVC animated:YES];
//}
//


#pragma mark - 按钮跳转到专辑页
//通过 pushActionDelegate 协议的 pushAction 方法实现
- (void)pushAction:(NSString *)str
{
    WMEAlbumViewController *album = [[WMEAlbumViewController alloc] init];
    album.interface = str;
    [self.navigationController pushViewController:album animated:YES];
}
#pragma mark - 按钮跳转俱乐部
- (void)pushClubAction:(NSString *)clubStr
{
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    //    __weak WMEUserViewController *vc = self;
    
    [data GET:clubStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"responseObject:%@", responseObject);
        
        NSArray *tempArr = responseObject[@"data"][@"object_list"];
        NSArray *clubArr = [WMEClubInformationModel modelHandlerWithArray:tempArr];
        WMEClubListViewController *club = [[WMEClubListViewController alloc] init];
        club.dataArr = clubArr;
        [self.navigationController pushViewController:club animated:YES];
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}
#pragma mark -pushImgView
- (void)pushImgViewAction:(NSString *)str
{
    WMEImageViewController *imgView = [[WMEImageViewController alloc] init];
    imgView.imgStr = str;
    [self.navigationController pushViewController:imgView animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
